package com.example.easyscript.utils.recognization;

import com.example.easyscript.dto.BaseMatchResult;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;

public class MatchTemplate {
    public static BaseMatchResult getTemplateCenterPoint(String templatePath, String sourcePath) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME) ;
        //将文件读入为OpenCV的Mat格式
        Mat source = Highgui.imread(sourcePath);
        Mat template = Highgui.imread(templatePath);
        //创建于原图相同的大小，储存匹配度
        //Mat result = Mat.zeros(source.rows() - template.rows() + 1, source.cols() - template.cols() + 1, CvType.CV_32FC1);
        Mat result = new Mat();
        //调用模板匹配方法
        Imgproc.matchTemplate(source, template, result, Imgproc.TM_SQDIFF_NORMED);
        //规格化
        Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1);
        //获得最可能点，MinMaxLocResult是其数据格式，包括了最大、最小点的位置x、y
        Core.MinMaxLocResult mlr = Core.minMaxLoc(result);
        Point matchLoc = mlr.minLoc;
        BaseMatchResult matchResult = new BaseMatchResult(matchLoc,template.rows(),template.cols()) ;
        return matchResult ;
    }
}
